import { TaskProgress, TaskLogEntry } from '../../shared/types'
import { logger } from '@roasmax/logger'
import { v4 as uuidv4 } from 'uuid'
import { BrowserWindow } from 'electron'
import { IPC_EVENTS } from '../../shared/constants'
import { useEntityManager } from '../storage/data-source'
import { Task, TaskLog } from '../storage/entities'

export class TaskIOManager {
  private mainWindow: BrowserWindow | null = null

  /**
   * 设置主窗口引用，用于发送实时更新
   */
  setMainWindow(window: BrowserWindow) {
    this.mainWindow = window
  }

  /**
   * 发送任务状态变化事件
   */
  sendTaskStatusChange(taskId: string, status: string) {
    if (this.mainWindow && !this.mainWindow.isDestroyed()) {
      this.mainWindow.webContents.send(IPC_EVENTS.TASK_STATUS_CHANGE, taskId, status)
    }
  }

  /**
   * 更新任务进度
   */
  async updateTaskProgress(taskId: string, progress: TaskProgress): Promise<void> {
    logger.info('更新任务进度', { taskId, progress })
    
    // 更新数据库中的任务进度
    await useEntityManager(async m => {
      const taskRepo = m.getRepository(Task)
      const taskEntity = await taskRepo.findOne({ where: { id: taskId } })
      
      if (taskEntity) {
        const task = taskEntity.toScrapeTask()
        task.progress = progress
        const updatedTaskEntity = Task.fromScrapeTask(task)
        await taskRepo.save(updatedTaskEntity)
      }
    })

    // 发送进度更新到前端
    if (this.mainWindow && !this.mainWindow.isDestroyed()) {
      logger.info('发送进度更新到前端', { taskId, progress })
      this.mainWindow.webContents.send(IPC_EVENTS.TASK_PROGRESS_UPDATE, taskId, progress)
    } else {
      logger.warn('主窗口不可用，无法发送进度更新', { taskId })
    }
  }

  /**
   * 添加任务日志
   */
  async addTaskLog(taskId: string, level: 'info' | 'warn' | 'error' | 'debug', message: string, data?: any): Promise<void> {
    // 改为保存到 TaskLog 表
    try {
      await useEntityManager(async m => {
        const taskLogRepo = m.getRepository(TaskLog)

        // 创建任务日志实体
        const taskLog = new TaskLog()
        taskLog.taskId = taskId
        taskLog.level = level
        taskLog.message = message
        taskLog.data = data
        taskLog.source = 'TaskManager'

        // 保存到数据库
        await taskLogRepo.save(taskLog)

        logger.debug('任务日志已保存', { taskId, level, message })
      })

      // 创建日志条目用于前端显示
      const logEntry: TaskLogEntry = {
        id: uuidv4(),
        timestamp: new Date(),
        level,
        message,
        data
      }

      // 发送日志更新到前端
      if (this.mainWindow && !this.mainWindow.isDestroyed()) {
        this.mainWindow.webContents.send(IPC_EVENTS.TASK_LOG_UPDATE, {
          taskId,
          logEntry
        })
      }
    } catch (error) {
      // 如果保存日志失败，至少要记录到控制台
      logger.error('保存任务日志失败', { taskId, level, message, error })
    }
  }

  /**
   * 批量发送任务状态更新
   */
  sendBatchTaskStatusUpdates(updates: Array<{ taskId: string; status: string }>) {
    if (this.mainWindow && !this.mainWindow.isDestroyed()) {
      for (const update of updates) {
        this.mainWindow.webContents.send(IPC_EVENTS.TASK_STATUS_CHANGE, update.taskId, update.status)
      }
    }
  }

  /**
   * 发送任务完成通知
   */
  sendTaskCompletionNotification(taskId: string, result: any) {
    if (this.mainWindow && !this.mainWindow.isDestroyed()) {
      this.mainWindow.webContents.send(IPC_EVENTS.TASK_COMPLETION, {
        taskId,
        result,
        timestamp: new Date()
      })
    }
  }

  /**
   * 发送任务错误通知
   */
  sendTaskErrorNotification(taskId: string, error: string) {
    if (this.mainWindow && !this.mainWindow.isDestroyed()) {
      this.mainWindow.webContents.send(IPC_EVENTS.TASK_ERROR, {
        taskId,
        error,
        timestamp: new Date()
      })
    }
  }

  /**
   * 检查主窗口是否可用
   */
  isMainWindowAvailable(): boolean {
    return this.mainWindow !== null && !this.mainWindow.isDestroyed()
  }
}
